package com.virus.mall.controller.mall;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.virus.mall.model.Result;
import com.virus.mall.model.Type;
import com.virus.mall.service.GoodsService;
import com.virus.mall.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Classname MallIndexServlet
 * @Description NULL
 * @Date 2021/4/20 14:27
 * @Created by virus
 */
@WebServlet("/api/mall/index/*")
public class MallIndexServlet extends HttpServlet {

    private GoodsService goodsService = new GoodsServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/mall/index/", "");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/mall/index/", "");
        if (op.equals("getType")) {
            getType(request, response);
        }
    }

    /**
     * 获得商品类型信息
     * @param request
     * @param response
     * @throws IOException
     */
    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> type = goodsService.getType();
        if (type == null) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("请求类型错误")));
            return;
        }
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(type)));
    }
}
